<?php

namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use util\File;
use function Symfony\Component\String\b;
use function Symfony\Component\String\u;

class WxUser extends Homebase
{
    protected $openid;
    protected $memberInfo;
    protected $memberId;
    protected $role;
    protected $noRule = ['getGoodsDetail','getGoodsAttr'];
    protected function initialize()
    {
        parent::initialize();
        $data = $this->request;
        if (!in_array($data->routeInfo()['rule'], $this->noRule)) {
            $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
            if (empty($authorization)) {
                responseJson(-100, '请先登录');
            }
            $this->openid = $authorization;
            $user = Db::name('member')->where('openid', '=', $this->openid)
                ->field('id,openid,nickname,avatarUrl,mobile,status,fraction,code_url,invite_id,money,level_id,is_clock')->find();
            if (empty($user)) {
                responseJson(-100, '登录信息有误');
            }
            if ($user['status'] == 0) {
                msg(-200, '用户已冻结', $user);
            }
            if (!strpos($user['avatarUrl'], 'ttp')) {
                $user['avatarUrl'] = config('wechat.url') . $user['avatarUrl'];
            }
            $this->memberInfo = $user;
            $this->memberId = $user['id'];
        }else{
            $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
            if ($authorization){
                $this->openid = $authorization;
                $user = Db::name('member')->where('openid', '=', $this->openid)
                    ->field('id,openid,nickname,avatarUrl,mobile,status,fraction,code_url,invite_id,money,level_id')->find();
                $this->memberInfo = $user;
                $this->memberId = $user['id'];
            }
        }
    }

    //商品详情
    public function getGoodsDetail()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')->find($data['id']);
        $brand = Db::name('brand')->find($goods_info['brand_id']);
        $goods_info['brand'] = $brand['name'];
        $goods_info['img'] = explode(',', $goods_info['img']);
        $goods_attr_value = Db::name('goods_attr_value')->where([
            'goods_id' => $data['id']
        ])->find();
        $goods_attr_value['price']-=getDiscountMoney($this->memberInfo,$data['id']);
        $goods_info['goods_attr_value'] = $goods_attr_value;
        if ($this->memberId){
            $goods_info['is_collect'] = $this->isCollect($data['id']);
        }else{
            $goods_info['is_collect'] = 0;
        }
        msg(0, '查询成功', $goods_info);
    }

    //商品规格
    public function getGoodsAttr()
    {
        $data = $this->request->param();
        $goods_attr_value = Db::name('goods_attr_value')->where([
            'goods_id' => $data['id']
        ])->select();
        foreach ($goods_attr_value as $k => $v) {
            if ($k==0){
                $goods_attr_value[$k]['is_select'] = 2;
            }else{
                $goods_attr_value[$k]['is_select'] = 1;
            }
            if ($this->memberId){
                $goods_attr_value[$k]['price'] -= getDiscountMoney($this->memberInfo,$data['id']);
            }
        }
        msg(0, '查询成功', $goods_attr_value);
    }

    /**
     * 获取用户信息
     */
    public function getMemberInfo()
    {
        //会员二维码
        if (!$this->memberInfo['code_url']) {
            $code_url = qrcode($this->memberId, '');
            Db::name('member')->update([
                'id' => $this->memberId,
                'code_url' => $code_url
            ]);
        }
        $level_info = Db::name('member_level')->find($this->memberInfo['level_id']);
        $this->memberInfo['level_info'] = $level_info;
        msg(0, '查询成功', $this->memberInfo);
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 修改用户信息
     */
    public function updateUserinfo()
    {
        $data = $this->request->param();
        $update_data = array();
        if (isset($data['mobile']) && $data['mobile']) {
            $update_data['mobile'] = $data['mobile'];
        }
        if (isset($data['nickname']) && $data['nickname']) {
            $update_data['nickname'] = $data['nickname'];
        }
        if (isset($data['avatarUrl']) && $data['avatarUrl']) {
            $update_data['avatarUrl'] = $data['avatarUrl'];
        }
        $stmt = Db::name('member')
            ->where('openid', $this->openid)
            ->update($update_data);
        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(-1, "修改失败", []);
        }
    }

    //获取地址列表
    public function getAddressList()
    {
        $member_id = $this->memberInfo['id'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $member_id];
        $data = Db::name('member_address')
            ->where($where)
            ->order('is_default_address desc')
            ->order('create_time desc')
            ->select();
        msg(0, "查询成功", $data);
    }

    //增加收货地址
    public function addAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'member_id' => $this->memberInfo['id'],
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('member_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $insert_id = Db::name('member_address')->insertGetId($save_data);
            Db::commit();
            msg(0, '添加成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //设置默认地址
    public function setDefaultAddress()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            Db::name('member_address')
                ->where(['member_id' => $this->memberId])
                ->update(['is_default_address' => 0]);
            $num = Db::name('member_address')
                ->where(['id' => $data['id']])
                ->update([
                    'is_default_address' => 1
                ]);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //编辑收货地址
    public function editAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('member_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $num = Db::name('member_address')
                ->where(['id' => $data['id']])
                ->update($save_data);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取默认地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getDefaultAddress()
    {
        $data = $this->getAddress();
        msg(0, '查询成功', $data);
    }

    public function getAddress()
    {
        $where[] = ['is_default_address', '=', 1];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberInfo['id']];
        $data = Db::name('member_address')->where($where)->find();
        return $data;
    }

    /**
     * 通过id获取地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getAddress2()
    {
        $data = $this->request->param();
        $addressData = $this->getAddressById($data['id']);
        msg(0, '查询成功', $addressData);
    }

    public function getAddressById($id)
    {
        return Db::name('member_address')->find($id);
    }

    //删除地址
    public function delAddress()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $data['address_id'],
            'is_del' => 1
        );
        $order_data = Db::name('member_address')->update($update);
        msg(0, "删除成功", $order_data);
    }

    /**
     * 清空购物车
     */
    public function clearCardList()
    {
        Db::name('goods_car')->where([
            'member_id' => $this->memberId
        ])->delete();
        msg(0, "删除成功", 1);
    }

    /**
     * 加入购物车
     */
    public function addGoodsCar()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['attr_name']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
                ->where($where)
                ->find();
//            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            if ($goods_info['stock'] < $data['num']) {
                msg(-1, '库存不足', '');
            }
            $is_on_car = Db::name('goods_car')->where([
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id'],
                'attr_name' => $data['attr_name']
            ])->find();
            if ($is_on_car) {
                Db::name('goods_car')->where([
                    'member_id' => $this->memberId,
                    'goods_id' => $data['goods_id'],
                    'attr_name' => $data['attr_name']
                ])->setInc('num', $data['num']);
            } else {
                $insert_data = array(
                    'goods_id' => $data['goods_id'],
                    'attr_name' => $data['attr_name'],
                    'member_id' => $this->memberId,
                    'num' => $data['num'],
                    'create_time' => time(),
                );
                Db::name('goods_car')->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function addGoodsCar2()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $goods = array(
                ['goods_id' => 29, 'attr_name' => "默认", 'num' => 1],
                ['goods_id' => 30, 'attr_name' => "200ml", 'num' => 2],
            );
            foreach ($data['goods'] as $k => $v) {
                $where = array(
                    'g.id' => $v['goods_id'],
                    'g.is_del' => 0,
                    'g.status' => 1,
                    'gav.suk' => $v['attr_name']
                );
                $goods_info = Db::name('goods')->alias('g')
                    ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                    ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
                    ->where($where)
                    ->find();
//                if (!$goods_info) {
//                    continue;
//                    msg(-1, '商品不存在', '');
//                }
                $is_on_car = Db::name('goods_car')->where([
                    'member_id' => $this->memberId,
                    'goods_id' => $v['goods_id'],
                    'attr_name' => $v['attr_name']
                ])->find();
                if ($is_on_car) {
                    Db::name('goods_car')->where([
                        'member_id' => $this->memberId,
                        'goods_id' => $v['goods_id'],
                        'attr_name' => $v['attr_name']
                    ])->setInc('num', $v['num']);
                } else {
                    $insert_data = array(
                        'goods_id' => $v['goods_id'],
                        'attr_name' => $v['attr_name'],
                        'member_id' => $this->memberId,
                        'num' => $v['num'],
                        'create_time' => time(),
                    );
                    Db::name('goods_car')->insertGetId($insert_data);
                }
                Db::commit();
            }

            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取购物车列表
    public function getGoodsCarList()
    {
        $data_list = Db::name('goods_car')
            ->alias('gc')->join('goods g', 'gc.goods_id=g.id')
            ->field('gc.*,g.name as goods_name,g.first_img,g.desc,g.is_del as goods_is_del')
            ->where(['member_id' => $this->memberId])
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $is_buy = 1;
            $goods_attr_value = Db::name('goods_attr_value')->where([
                'goods_id' => $v['goods_id'],
                'suk' => $v['attr_name']
            ])->order('id')->find();
            if (!$goods_attr_value || $v['goods_is_del']) {
                $is_buy = 0;
            }
            $goods_attr_value['price'] -= getDiscountMoney($this->memberInfo,$v['goods_id']);
            $data_list[$k]['goods_attr_value'] = $goods_attr_value;
            $data_list[$k]['is_buy'] = $is_buy;
            $data_list[$k]['sumPrice'] = round($data_list[$k]['num'] * $goods_attr_value['price'], 2);
        }
        msg(0, '添加完成', $data_list);
    }

    //删除购物车商品
    public function delGoodsCarList()
    {
        $data = $this->request->param();
        Db::name('goods_car')
            ->where('id', 'in', $data['goods_car_ids'])
            ->delete();
        msg(0, '删除完成', '');
    }

    //修改购物车商品数量
    public function updateGoodsCardList()
    {
        $data = $this->request->param();
        Db::name('goods_car')
            ->where(['id' => $data['goods_car_id']])
            ->update(['num' => $data['num']]);
        msg(0, '修改完成', '');
    }

    //视频列表
    public function videoList2()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $data_list = Db::name('video')->where($where)
            ->order('sort desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['isKan'] = $this->isKan($item['id']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    public function isKan($video_id)
    {
        $info = Db::name('member_video')
            ->where([
                'member_id' => $this->memberId,
                'video_id' => $video_id
            ])
            ->find();
        if ($info) {
            return 1;
        }
        return 0;
    }

    //视频详情
    public function videoDetail()
    {
        $data = $this->request->param();
        $video = Db::name('video')->find($data['id']);
        //todo 后台可改
        $video['effect_second']=24;
        msg(0, '修改完成', $video);
    }

    //看完视频调用
    public function seeFinishVideo()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $is_kan = $this->isKan($data['id']);
            if (!$is_kan) {
                $video = Db::name('video')->find($data['id']);
                $insert_data = array(
                    'member_id' => $this->memberId,
                    'video_id' => $data['id'],
                    'points' => $video['points'],
                    'create_time' => time()
                );
                Db::name('member_video')->insertGetId($insert_data);
                addFraction($this->memberId, $video['points'], '用户看视频');
            }
//            else{
//                msg(-1, '视频已观看', '');
//            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //商城兑换
    //积分兑换
    public function fractionExchange()
    {
        $data = $this->request->param();
        $goods_info = Db::name('points_goods')->where(['id' => $data['id']])->find();
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        Db::startTrans();
        try {
            if ($goods_info['points'] > $this->memberInfo['fraction']) {
                msg(-1, '积分不足', '');
            }
            $insert_goods_order_data = array(
                'no' => GetOrderSN(2),
                'goods_id' => $data['id'],
                'member_id' => $this->memberId,
                'create_time' => time(),
                'points' => $goods_info['points'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['img']
            );
            $insert_goods_order_data['is_express'] = 1;
            $insert_goods_order_data['realname'] = $data['people'];
            $insert_goods_order_data['telphone'] = $data['phone'];
            $insert_goods_order_data['province'] = $data['province'];
            $insert_goods_order_data['city'] = $data['city'];
            $insert_goods_order_data['area'] = $data['area'];
            $insert_goods_order_data['address'] = $data['address'];
            $goods_order_id = Db::name('points_goods_order')->insertGetId($insert_goods_order_data);
            //兑换数量
            Db::name('points_goods')->where('id', '=', $data['id'])->setInc('sale_num');
            addFraction($this->memberId, $goods_info['points'], '积分兑换', 2, 2);
            Db::commit();
            msg(0, '兑换成功', $goods_order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //兑换记录
    public function PGoodsOrderList()
    {
        //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货7已取消
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberId];
        if (isset($data['status']) && $data['status']) {
            $where[] = ['status', '=', $data['status']];
        }else{
            $where[] = ['status', '<>', 7];
        }
        $data_list = Db::name('points_goods_order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {

                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //积分商品订单详情
    public function PGoodsOrderDetail()
    {
        $data = $this->request->param();
        $data = Db::name('points_goods_order')->find($data['id']);
        msg(0, '查询成功', $data);
    }

    //积分明细
    public function fractionHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //cate 0收入 1支出
        $type = $data['cate'];
        $where[] = ['member_id', '=', $this->memberId];
        if ($type == 0) {
            $where[] = ['is_count', '=', 1];
        } elseif ($type == 1) {
            $where[] = ['is_count', '=', 2];
        }
        $data_list = Db::name('fraction_record')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    /**
     * 收藏物品
     */
    public function collectGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $is_collect = Db::name('collect_goods')->where([
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            ])->find();
            if ($is_collect) {
                msg(-2, '商品已收藏', '');
            }
            $insert_data = array(
                'create_time' => time(),
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            );
            Db::name('collect_goods')->insertGetId($insert_data);
            Db::commit();
            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 取消收藏
     */
    public function cancelCollectGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
//            $goods_info = Db::name('goods')
//                ->where(['id' => $data['goods_id']])
//                ->find();
//            if (!$goods_info) {
//                msg(-1, '商品不存在', '');
//            }
//            $where = array(
//                'member_id' => $this->memberId,
////                'goods_id' => $data['goods_id']
//            );
            Db::name('collect_goods')->where([
                ['member_id', '=', $this->memberId],
                ['goods_id', 'in', $data['goods_id']],
            ])->delete();
            Db::commit();
            msg(0, '取消收藏', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断商品是否收藏
    public function isCollect($goods_id)
    {
        $is_collect = Db::name('collect_goods')->where([
            'goods_id' => $goods_id,
            'member_id' => $this->memberId
        ])->find();
        if ($is_collect) {
            return 1;
        }
        return 0;
    }

    //收藏列表
    public function collectList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $data_list = Db::name('collect_goods')->alias('c')
            ->join('goods g', 'c.goods_id=g.id')
            ->field('c.*,g.name as goods_name,g.first_img,g.desc')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['goods_price'] = Db::name('goods_attr_value')->where([
                    'goods_id' => $item['id']
                ])->find();
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }
    //todo 收藏商品 收藏列表 删除商品规格名称都删除
    // 直接购买创建订单 购物车结算创建订单 发起支付 支付回调 订单列表
    // 订单详情
    // 后台订单管理 对接oss 对接微信支付
    // 后台优惠券
    // 优惠券发送

    // 直接购买创建订单
    public function createOrder()
    {
        $data = $this->request->param();
        //判断库存 是否可买
        $where = array(
            'g.id' => $data['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
            'pay_status' => 0,
            'create_time' => time(),
            'people' => $data['people'],
            'phone' => $data['phone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'remark' => $data['remark'],
        );
        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        //计算折扣
        $goods[] = array(
            'goods_id' => $data['goods_id'],
            'num' => $data['num'],
            'attr' => $data['suk']
        );
        $discount_money = getDiscountMoney($this->memberInfo,$data['goods_id'])* $data['num'];
        $insert_data['discount_money'] = $discount_money;
        $insert_data['order_money'] -= $discount_money;
        if (isset($data['mc_id']) && $data['mc_id']) {
            $coupons_where = array(
                'member_id' => $this->memberId,
                'id' => $data['mc_id'],
                'status' => 1,
                'is_del' => 0,
            );
            $member_coupons = Db::name('member_coupons')
                ->where($coupons_where)
                ->find();
            if (!$member_coupons) {
                msg(-1, '优惠券不存在', '');
            }
            if ($insert_data['order_money'] < $member_coupons['min_amount']) {
                msg(-1, '优惠券不可用', '');
            }
            $insert_data['mc_id'] = $data['mc_id'];
            $insert_data['coupon_money'] = $member_coupons['value'];
            $insert_data['order_money'] = round($insert_data['origin_price'] - $member_coupons['value'], 2);
        }
        $insert_data['pay_money'] = $insert_data['order_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['mc_id']) && $data['mc_id']) {
                //优惠券状态修改
                Db::name('member_coupons')->update(
                    [
                        'id' => $data['mc_id'],
                        'status' => 2,
                        'used_time' => time(),
                        'order_id' => $order_id
                    ]
                );
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price']-getDiscountMoney($this->memberInfo,$data['goods_id']),
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money'=>$data['num']*($goods_info['price']-getDiscountMoney($this->memberInfo,$data['goods_id']))
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 购物车订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrder2()
    {
        $data = $this->request->param();
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
            'pay_status' => 0,
            'create_time' => time(),
            'people' => $data['people'],
            'phone' => $data['phone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'remark' => $data['remark'],
        );
        $insert_data['origin_price'] = 0;
        //检查商品是否存在 检测商品库存
        $goods_info2 = [];
        $goods_car_list = Db::name('goods_car')->where([
            ['id', 'in', $data['goods_car_ids']],
            ['member_id', '=', $this->memberId]
        ])->select();
        if (!$goods_car_list) {
            msg(-1, '购物车不存在', '');
        }
        foreach ($goods_car_list as $k => $v) {
            $where = array(
                'g.id' => $v['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $v['attr_name'],
                'gc.member_id' => $this->memberId
            );
            $goods_car_list[$k]['attr'] = $v['attr_name'];
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->join('goods_car gc', 'gc.goods_id=g.id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gc.num as gc_num,gc.member_id')
                ->where($where)
                ->find();
            if (!$goods_info) {
                msg(-1, '商品' . $goods_info['name'] . '不存在,或下架', '');
            }
            if ($goods_info['stock'] < $v['num']) {
                msg(-2, '商品' . $goods_info['name'] . '库存不足', '');
            }
            $goods_info2[] = $goods_info;
            $insert_data['origin_price'] += $goods_info['price'] * $v['num'];
        }
        $insert_data['origin_price'] = round($insert_data['origin_price'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        //计算折扣
        $discount_money = $this->getDisCountMoney($goods_car_list);
        $insert_data['discount_money'] = $discount_money;
        $insert_data['order_money'] -= $discount_money;
        if (isset($data['mc_id']) && $data['mc_id']) {
            $coupons_where = array(
                'member_id' => $this->memberId,
                'id' => $data['mc_id'],
                'status' => 1,
                'is_del' => 0,
            );
            $member_coupons = Db::name('member_coupons')
                ->where($coupons_where)
                ->find();
            if (!$member_coupons) {
                msg(-1, '优惠券不存在', '');
            }
            if ($insert_data['order_money'] < $member_coupons['min_amount']) {
                msg(-1, '优惠券不可用', '');
            }
            $insert_data['mc_id'] = $data['mc_id'];
            $insert_data['coupon_money'] = $member_coupons['value'];
            $insert_data['order_money'] = round($insert_data['origin_price'] - $member_coupons['value'], 2);
        }
        $insert_data['pay_money'] = $insert_data['order_money'];
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time2'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time2'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['mc_id']) && $data['mc_id']) {
                //优惠券状态修改
                Db::name('member_coupons')->update(
                    [
                        'id' => $data['mc_id'],
                        'status' => 2,
                        'used_time' => time(),
                        'order_id' => $order_id
                    ]
                );
            }
            foreach ($goods_info2 as $k2 => $v2) {
                $insert_order_goods = array(
                    'order_id' => $order_id,
                    'goods_id' => $v2['id'],
                    'suk' => $v2['suk'],
                    'num' => $v2['gc_num'],
                    'price' => $v2['price']-getDiscountMoney($this->memberInfo, $v2['id']),
                    'goods_name' => $v2['name'],
                    'goods_img' => $v2['first_img'],
                    'sum_money'=>$v2['gc_num']*($v2['price']-getDiscountMoney($this->memberInfo, $v2['id']))
                );
                Db::name('order_goods')->insertGetId($insert_order_goods);
            }
            //删除购物车
            Db::name('goods_car')->where('id', 'in', $data['goods_car_ids'])->delete();
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断优惠券是否能用
    public function getMemberCouponAble()
    {
        $data = $this->request->param();
        $member_coupons_list = Db::name('member_coupons')->where([
            ['member_id', '=', $this->memberId],
            ['min_amount', '<', $data['money']],
        ])->select();
        msg(0, '创建完成', $member_coupons_list);
    }

    //订单发起支付
    public function orderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //订单回调
    public function orderPayBack()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            //todo 支付成功测试
//            if ($order_data['status'] == 1) {
//                orderPaySuccess($order_data);
//            }
//            Db::commit();
//            msg(0, "支付成功！", $order_data);
            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 1) {
                    orderPaySuccess($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
//            return $e;
            msg(-1, $e->getMessage(), '');
        }

    }
    //订单列表 status 1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    // 0全部 1待支付 2待发货 3待收货 4已完成 5收货退货
    public function orderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberId];
        if ($data['type'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 5, 6]];
        }
        if (isset($data['type']) && $data['type']) {

            if ($data['type'] == 4) {
                  $where[] = ['status', 'in', [4, 5]];
            } elseif($data['type'] == 5){
                $where[] = ['status', 'in', [6]];
            }else {
                $where[] = ['status', '=', $data['type']];
            }
        }
        $order_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time2'] = $item['create_time'];
                $item['dai_zf_time1'] = $item['create_time'] + (60 * 15);
                $item['dai_zf_time'] = date('Y-m-d H:i:s', $item['create_time'] + (60 * 15));
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['tui_time']) {
                    $item['tui_time'] = date('Y-m-d H:i:s', $item['tui_time']);
                }
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->select();
                $item['order_goods'] = $order_goods;
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }


    public function orderDetail()
    {
        $data = $this->request->param();
           $return_detail = Db::name('order')->where('order_no','=',$data['id'])->find();
        if (!$return_detail) {
            msg(-1, '订单不存在', '');
        }
        if ($return_detail['status']==1){
            $return_detail['dai_zf_time1'] = $return_detail['create_time'];
            $return_detail['dai_zf_time2'] = $return_detail['create_time'] + (60 * 15);
        }

        $return_detail['create_time'] = date('Y-m-d H:i:s', $return_detail['create_time']);
        if ($return_detail['pay_time']) {
            $return_detail['pay_time'] = date('Y-m-d H:i:s', $return_detail['pay_time']);
        }
        if ($return_detail['tui_time']) {
            $return_detail['tui_time'] = date('Y-m-d H:i:s', $return_detail['tui_time']);
        }
        if ($return_detail['send_time']) {
            $return_detail['send_time'] = date('Y-m-d H:i:s', $return_detail['send_time']);
        }


        $order_goods = Db::name('order_goods')
            ->where('order_id', '=', $data['id'])
            ->select();
        $return_detail['order_goods'] = $order_goods;
        msg(0, '查询成功', $return_detail);
    }

    //完成收货 '1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货\r\n7已取消
    public function finishOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->find($data['id']);
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
//        if ($order_info['member_id']!=$this->memberId){
//            msg(-1, '订单不属于本用户', '');
//        }
        //todo  上线打开
//        if ($order_info['status']!=3){
//            msg(-1, '订单未发货不可完成', '');
//        }
        Db::startTrans();
        try {
            finishOrder($order_info);
            orderFinish($order_info['member_id'], $order_info);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //取消订单
    public function cancelOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->find($data['id']);
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        if ($order_info['member_id']!=$this->memberId){
            msg(-1, '订单不属于本用户', '');
        }
//        todo  上线打开
        if ($order_info['status']!=1){
            msg(-1, '订单不可取消', '');
        }
        Db::startTrans();
        try {
            Db::name('order')->update([
                'id'=>$data['id'],
                'status'=>7,
            ]);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //获取退款原因
    public function tuiReason()
    {
        $data_list = Db::name('refund_reason')
            ->where([
                'is_del' => 0,
                'status' => 1
            ])->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //订单退款 status 1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    public function tuiOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->where('order_no','=',$data['id'])->find();
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        //2 直接退款 3,4,5需要寄回退款 1,6无法退款 todo 上线进行关闭
//        if ($order_info['status']==1||$order_info['status']==6){
//            msg(-1, '当前订单不可退款', '');
//        }
        Db::startTrans();
        try {
            $order_after = array(
                'tui_no' => 'cp' . GetOrderSN(2),
                'order_no' => $order_info['order_no'],
                'order_id' => $order_info['id'],
                'status' => 1,
                'create_time' => time(),
                'tui_reason' => $data['tui_reason'],
                'order_pay_money' => $order_info['pay_money'],
                'member_id' => $order_info['member_id'],
                'is_fa' => 1,
                'order_status' => $order_info['status']
            );
            if ($data['imgs']) {
                $order_after['imgs'] = implode(',', $data['imgs']);
            }
            if ($order_info['status'] == 2) {
                $order_after['is_fa'] = 0;
            }
            Db::name('order_after')->insertGetId($order_after);
            $update_date = array(
                'id' => $order_info['id'],
                'status' => 6,
                'tui_before' => $order_info['status']
            );
            Db::name('order')->update($update_date);
            Db::commit();
            msg(0, '申请完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //退款详情
    public function orderTuiDetail()
    {
        $data = $this->request->param();
        $where[] = ['order_no', '=', $data['id']];
        $order_info = Db::name('order')
            ->where('order_no', '=', $data['id'])
            ->find();
        $order_after = Db::name('order_after')
            ->order('create_time desc')
            ->where($where)
            ->find();
        if (!$order_after) {
            $order_info['type_status'] = 0;
        } else {
            $order_info['type_status'] = $order_after['status'];
        }
        if ($order_after['finishi_time']) {
            $order_after['finishi_time'] = date('Y-m-d H:i:s', $order_after['finishi_time']);
        }
        if ($order_after['status_time']) {
            $order_after['status_time'] = date('Y-m-d H:i:s', $order_after['status_time']);
        }
        if ($order_after['send_time']) {
            $order_after['send_time'] = date('Y-m-d H:i:s', $order_after['send_time']);
        }
        $order_after['create_time'] = date('Y-m-d H:i:s', $order_after['create_time']);
        $order_after['copy_address_info'] = $order_after['people'] . ',' . $order_after['phone'] . ',' . $order_after['address'];
        $goods_info = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->select();
        $order_info['order_after'] = $order_after;
        $order_info['goods_info'] = $goods_info;
        msg(0, '查询完成', $order_info);
    }

    //退款发货
    public function tuiSendOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order_after')
            ->where('id', '=', $data['order_after_id'])
            ->find();
        if (!$order_info) {
            msg(-2, '售后订单不存在', '');
        }
        if (!in_array($order_info['status'],[2,4])) {
            msg(-1, '当前售后不可退货', '');
        }
        $update = array(
            'id' => $data['order_after_id'],
            'express' => $data['express'],
            'express_no' => $data['express_no'],
            'is_send' => 1,
            'send_time' => time(),
            'status' => 4
        );
        Db::startTrans();
        try {
            Db::name('order_after')->update($update);
            Db::commit();
            msg(0, '发货完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //更改邀请
    public function editInvite()
    {
        $data = $this->request->param();
        if ($this->memberId['is_clock']==1) {
            msg(0, '修改完成', '');
        }
        if (isset($data['invite_id'])) {
            $invite_data = getInvite($data['invite_id']);
            if ($invite_data['invite_id'] > 0) {
                $update = array(
                    'id' => $this->memberId,
                    'invite_id' => $invite_data['invite_id'],
                    'boss_invite_id' => $invite_data['boss_invite_id'],
                    'top_invite_id' => $invite_data['top_invite_id'],
                );
                Db::name('member')->update($update);
            }
        }
        msg(0, '修改完成', '');
    }

    public function teamMoney()
    {
        $year = $this->request->param('year', date('Y'));
        $month = $this->request->param('month', date('m'));
        $data=teamMoney($year,$month,$this->memberId);
        msg(0, '修改完成', $data);
    }
    /**
     * 用户金融相关
     **/
    //用户中心顶部相关三个参数
    public function memberTop()
    {
        $a = $this->memberInfo['money'];
        //团队
        $team_ids = getTeamMembersRecursive($this->memberId);
        array_unshift($team_ids, $this->memberId);
        $b = count($team_ids);
        $c = $this->memberInfo['fraction'];
        $data['a'] = $a;
        $data['b'] = $b;
        $data['c'] = $c;
        msg(0, '修改完成', $data);
    }

    //用户中心团队业绩
    public function teamPerformance()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
//        $year = $this->request->param('year', date('Y'));
//        $month = $this->request->param('month', date('m'));
            $time = $data['time'];
            $time = explode('-', $time);
            $year = $time[0];
            $month = $time[1];
            $team_ids = getTeamMembersRecursive_time($this->memberId, $year, $month);
            array_unshift($team_ids, $this->memberId);
            $b = count($team_ids);
            $a = teamMoney($year, $month, $this->memberId);
            $a = $a['money'];
            $timeScope = getTimeScope($year . '-' . $month);
            $team_order_num = Db::name('order')->where([
                ['member_id', 'in', $team_ids],
                ['status', 'in', [4, 5]],
                ['finish_time', 'between', [$timeScope['startTimestamp'], $timeScope['endTimestamp']]]
            ])->count();
            $return_data['a'] = $a;
            $return_data['b'] = $b;
            $return_data['c'] = $team_order_num;
            Db::commit();
            msg(0, '修改完成', $return_data);
        } catch (\Exception $e) {
            dump($e);
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 提现
     */
    public function tixian()
    {
        $data = $this->request->param();
        if ($data['money'] <= 0) {
            msg(-1, '输入正确值', '');
        }
        if ($data['money'] > $this->memberInfo['money']) {
            msg(-1, '提现金额不能大于余额', '');
        }
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'money' => $data['money'],
                'type' => 8,
                'tixian_type' => $data['tixian_type'], //1银行 2支付宝 3微信
                'tixian_account' => $data['tixian_account'], //提现账号
                'tixian_name' => $data['tixian_name'],//提现人姓名
                'tixian_bank' => $data['tixian_bank'],//提现银行名（银行提现使用）
                'desc' => '余额提现',
                'status' => 0,//'0未完成 待审核 1已完成 审核完成 提现使用',
                'create_time' => time(),
                'is_count' => 2
            );
            $insert_data['shou_money'] = round($data['money'] * (0.07), 2);
            $insert_data['true_money'] = $data['money'] - $insert_data['shou_money'];
            $insert_id = Db::name('member_finance')->insertGetId($insert_data);
            Db::name('member')
                ->where('id', '=', $this->memberId)
                ->setDec('money', $data['money']);
            Db::commit();
            msg(0, '申请成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //提现记录
    public function tixianList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['type', '=', 8];
        $data_list = Db::name('member_finance')
            ->where($where)
            ->order('create_time desc')
            ->page($page, $length)
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $data_list[$k]['status_time'] = date('Y-m-d H:i:s', $v['status_time']);
            $data_list[$k]['kuan_time'] = date('Y-m-d H:i:s', $v['kuan_time']);
        }
        msg(0, '查询成功', $data_list);
    }

    //账户中心四个
    public function accountCenter()
    {
        $a = $this->memberInfo['money'];
        $b = Db::name('reward')->where([
            'member_id' => $this->memberId,
            'status' => 0
        ])->sum('money');
        $c = Db::name('member_finance')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 8],
            ['is_kuan', '=', 0],
        ])->sum('money');
        $d = Db::name('member_finance')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 8],
            ['is_kuan', '=', 1],
        ])->sum('money');
        $return['a'] = $a;
        $return['b'] = $b;
        $return['c'] = $c;
        $return['d'] = $d;
        msg(0, '查询成功', $return);
    }

    //收入明细 1推广奖2直推奖3间推奖4平级奖
    public function shouDetailList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $order_list = Db::name('reward')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['member_info'] = Db::name('member')->field('nickname,avatarUrl')->find($item['junior_member_id']);
                $item['goods_info'] = Db::name('goods')->field('name,first_img')->find($item['goods_id']);
                $price = Db::name('goods_attr_value')->where([
                    'goods_id' => $item['goods_id']
                ])->find();
                $item['goods_info']['price'] = $price['price'];
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //我的团队
    public function myTeam()
    {
        //获取下级ids
        $child_ids = getTeamMembersRecursive($this->memberId);
        $data = array();
        foreach ($child_ids as $k => $v) {
            $data[$k]['member_info'] = Db::name('member')
                ->field('id,nickname,avatarUrl,create_time')
                ->find($v);
            $data[$k]['member_info']['create_time'] = date('Y-m-d H:i:s', $data[$k]['member_info']['create_time']);
            $data[$k]['money'] = Db::name('reward')->where([
                ['junior_member_id', '=', $data[$k]['member_info']['id']],
                ['member_id', '=', $this->memberId],
                ['status', '=', 1],
            ])->sum('money');
            $data[$k]['order_num'] = Db::name('reward')->where([
                ['junior_member_id', '=', $data[$k]['member_info']['id']],
                ['member_id', '=', $this->memberId],
                ['status', '=', 1],
            ])->count();
            $data[$k]['team_num'] =count(getTeamMembersRecursive($v));
        }
        msg(0, '查询成功', $data);
    }

    //用过某个商品获取折扣
//    public function Discount()
//    {
//        $data = $this->request->param();
//        $disCOunt=$this->Discount2($data['goods_id']);
//        $c=0;
//        if ($disCOunt<100){
//            $c=1;
//        }
//        msg(0, '查询成功', $disCOunt,$c);
//    }
    //用过某个商品获取折扣数组
//    public function Discount22()
//    {
//        $data = $this->request->param();
//        $return_data=array();
//        $c=0;
//        $goods_car_list=Db::name('goods_car')->where('id','in',$data['goods_car_id'])->select();
//        foreach ($goods_car_list as $k=>$v){
//            $return_data[$k]['goods_card_id']=$v['id'];
//            $return_data[$k]['num']=$v['num'];
//            $return_data[$k]['goods_id']=$v['goods_id'];
//            $return_data[$k]['discount']=$this->Discount2($v['goods_id']);
//            $goods_attr_value=Db::name('goods_attr_value')->where([
//                'goods_id'=>$v['goods_id'],
//                'suk'=>$v['attr_name']
//            ])->find();
//            $return_data[$k]['price']=$goods_attr_value['price'];
//            if ( $return_data[$k]['discount']<100){
//                $c=1;
//            }
//        }
//        msg(0, '查询成功', $return_data,$c);
//    }



    //判断当前等级商品是否可购买
    public function isCanBuy()
    {
        $data = $this->request->param();
        $goods=Db::name('goods')->find($data['goods_id']);
        $return=$this->isBuy2($goods);
        if ($return==-1){
            msg(-1, '商品不可购买', '');
        }
        msg(0, '商品可购买', '');
    }

    //商品是否可购买
    public function isBuy2($goods)
    {
        if ($goods['is_limit_level']==1){
            $goods_level_buy=Db::name('goods_level_buy')->where([
                ['goods_id','=',$goods['id']],
                ['level_id','=',$this->memberInfo['level_id']],
            ])->find();
            if (!$goods_level_buy){
                return -1;
            }
        }
        return $goods;
    }

    //获取折扣金额
    public function getDisCountMoney($goods)
    {
        $getMoney = 0;
        //id attr num
        foreach ($goods as $k => $v) {
            $goods_attr_value = Db::name('goods_attr_value')->where([
                'goods_id' => $v['goods_id'],
                'suk' => $v['attr'],
            ])->find();
            if ($goods_attr_value) {
                $c=getDiscountMoney($this->memberInfo,$v['goods_id'])* $v['num'];
                $getMoney += $c;
            }
        }
        return $getMoney;
    }

    //复购获取上级
    public function getUpperLevelIds2(){
        $data = $this->request->param();
        $return_data=getUpperLevelIds3($data['member_id']);
        msg(0, '', $return_data);
    }
    //复购奖励测试
    public function reBuyReward(){
        $data = $this->request->param();
        $member=Db::name('member')->find($data['member_id']);
        $return_data= reBuyReward2(12,$member);
        msg(0, '查询完成', $return_data);
    }

    //todo 裕明合客户沟通 上传商品数据 测试 接口修改 ，悦巴赫操作文档 售后接口修改，物价网 验证码相关功能测试 上传项目
}
